package com.youlu.campus.service.course;

//import com.ctrip.framework.apollo.Config;
//import com.ctrip.framework.apollo.ConfigService;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityPlatformConfig;
import com.youlu.campus.entity.SystemApolloConfig;
import com.youlu.campus.entity.UserInfoExtend;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.WechatMiniUserPO;
import com.youlu.campus.entity.course.ActivityCourse;
import com.youlu.campus.entity.course.ActivityCourseVideo;
import com.youlu.campus.entity.course.UserCourseVideoStudy;
import com.youlu.campus.entity.course.dto.CourseInfoDTO;
import com.youlu.campus.entity.course.dto.HotActivityDTO;
import com.youlu.campus.entity.course.dto.KosActivityDTO;
import com.youlu.campus.entity.course.dto.RecommendActivityDTO;
import com.youlu.campus.entity.course.dto.RegisterActivityDTO;
import com.youlu.campus.entity.course.dto.ThirdCourseDTO;
import com.youlu.campus.entity.course.dto.UserActivityDTO;
import com.youlu.campus.entity.course.dto.UserLogoSaveDTO;
import com.youlu.campus.entity.course.dto.UserVideoDTO;
import com.youlu.campus.entity.course.entity.CourseSimpleActivityEntity;
import com.youlu.campus.entity.course.vo.ActivityResultVo;
import com.youlu.campus.entity.course.vo.CourseInfoVo;
import com.youlu.campus.entity.course.vo.CourseOrderVo;
import com.youlu.campus.entity.course.vo.CourseVideoVo;
import com.youlu.campus.entity.course.vo.KosActivityDetailVo;
import com.youlu.campus.entity.course.vo.RecruitmentActivityDetailVo;
import com.youlu.campus.entity.course.vo.RegisterActivityDetailVo;
import com.youlu.campus.entity.enums.ActivityVideoStatusEnum;
import com.youlu.campus.entity.enums.CourseVideoEnum;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.activity.UserActivityTaskInfoService;
import com.youlu.campus.service.activity.WechatMiniQaService;
import com.youlu.campus.service.base.LockService;
import com.youlu.campus.service.course.convert.LiteHomeCourseConvert;
import com.youlu.campus.service.invite.UserInviteRecordService;
import com.youlu.campus.service.kos.UserKosService;
import com.youlu.campus.service.system.SystemApolloConfigService;
import com.youlu.campus.service.utils.CryptoDEUtil;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import com.youlu.campus.service.visitor.UserPointsCourseStudyService;
import com.youlu.campus.service.vote.SimpleActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author : [dengbo]
 * @className : LiteHomeController
 * @description : [描述说明该类的功能]
 * @createTime : [2022/5/17 18:07]
 */
@Service
@Slf4j
public class LiteHomeService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserVideoService userVideoService;

    @Autowired
    private LockService lockService;

    @Autowired
    private LiteHomeCourseConvert liteHomeCourseConvert;

    @Autowired
    private UserCourseOrderService userCourseOrderService;

    @Autowired
    private UserPointsCourseStudyService userPointsCourseStudyService;

    @Autowired
    private WechatMiniQaService wechatMiniQaService;

    @Autowired
    private UserInviteRecordService userInviteRecordService;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    @Autowired
    private SimpleActivityService simpleActivityService;

    @Autowired
    private UserKosService userKosService;

    @Autowired
    private MiliThirdService miliThirdService;
    @Lazy
    @Autowired
    private UserActivityTaskInfoService userActivityTaskInfoService;
    @Autowired
    private ActivityTaskService activityTaskService;
    @Autowired
    private SystemApolloConfigService systemApolloConfigService;

    public ActivityCourse findByCourseId(String courseId) {
        return this.mongoTemplate.findById(courseId, ActivityCourse.class);
    }

    /**
     * 视频信息
     *
     * @param dto
     * @return
     */
    public CourseInfoVo getCourseInfo(CourseInfoDTO dto) {
        log.info(":>>> 开始获取课程信息:{}", JSON.toJSON(dto));
        // 1、查询活动信息
        QueryWrapper activeQuery = new QueryWrapper();
        activeQuery.select("id", "csInfos", "wxMiniOfficialQrcode", "courseId", "hasElectronicCa", "hasPaperCa",
                "startTime", "endTime", "subTitle", "type", "name", "showJoinNum", "initJoinNum", "randomInitJoinNum", "submitGanWu");
        activeQuery.where("id", dto.getActivityId());
        CourseSimpleActivityEntity activityInfo = mongoTemplate.findOne(activeQuery, CourseSimpleActivityEntity.class);
        if (activityInfo == null) {
            throw new BusinessException("活动信息不存在");
        }
        // 2、查询课程
        if (activityInfo.getCourseId() == null) {
            throw new BusinessException("课程信息不存在");
        }
        String courseId = activityInfo.getCourseId();
        Query courseQuery = new Query(Criteria.where("id").is(courseId).and("deleted").is(false));
        ActivityCourse activityCourse = mongoTemplate.findOne(courseQuery, ActivityCourse.class);
        if (activityCourse == null) {
            throw new BusinessException("课程信息不存在");
        }
        // 3.查询视频
        Query query = new Query(Criteria.where("courseId").is(activityCourse.getId()).and("valid").is(1));
        query.with(Sort.by(Sort.Order.desc("priority")));
        List<ActivityCourseVideo> videoList = mongoTemplate.find(query, ActivityCourseVideo.class);
        // 4、数据处理
        CourseInfoVo courseInfoVo = liteHomeCourseConvert.activityCourseDTOToCourse(activityInfo, activityCourse, videoList);
        // 5.获取活动状态
        UserActivityDTO userActivityInfo = userVideoService.getUserActivityInfo(dto.getUserId(), dto.getAppId(), dto.getActivityId());
        courseInfoVo.setQaInfoId(userActivityInfo.getQaInfoId());
        // 根据活动类型设置状态
//        /**
//         *     TODO("待上传", -1),
//         *     UN_LOCK_COURSE("解锁课程", 0),
//         *     STUDYING("观看学习", 1),
//         *     DO_THE_TITLE("考试答题", 2),
//         *     RECEIVE_CERTIFICATE("领取证书",3),
//         *     PASS("审核通过",4),
//         *     NOT_PASS("审核不通过",5)
//         *     6:待审核
//         */
//        if (Boolean.TRUE.equals(activityInfo.getSubmitGanWu())) {
//            if (userActivityInfo.getStatus() == 0) {
//                courseInfoVo.setActivityStatus(0);
//            } else if(userActivityInfo.getStatus() == 1){
//                courseInfoVo.setActivityStatus(1);
//            }else {
//                ActivityTaskInfo taskInfo = activityTaskService.find(dto.getActivityId(), TaskBizType.SHOW_STYLE);
//                if (Objects.isNull(taskInfo)) {
//                    log.error(":>>> 活动:{},没有配置风采展示", dto.getActivityId());
//                    throw new BusinessException("活动配置错误,请联系客服!");
//                } else {
//                    UserActivityTaskInfo userActivityTaskInfo = userActivityTaskInfoService.find(dto.getUserId(), dto.getActivityId(), taskInfo.getId());
//                    log.info(":>>> 用户:{},活动:{},任务状态:{}", dto.getUserId(), dto.getActivityId(), userActivityTaskInfo == null ? null : userActivityTaskInfo.getStatus());
//                    if (Objects.isNull(userActivityTaskInfo)) {
//                        // 待上传
//                        courseInfoVo.setActivityStatus(2);
//                    } else {
//                        /**
//                         * 状态userActivityTaskInfo.getStatus()
//                         * -1:待上传,0:未报名,1:待审核,2:审核通过,3:审核不通过,4:已领取
//                         */
//                        switch (userActivityTaskInfo.getStatus()) {
//                            case 0:
//                                courseInfoVo.setActivityStatus(-1);
//                                break;
//                            case 1:
//                                courseInfoVo.setActivityStatus(6);
//                                break;
//                            case 2:
//                                courseInfoVo.setVerifyComment(userActivityTaskInfo.getVerifyComment());
//                                courseInfoVo.setActivityStatus(4);
//                                break;
//                            case 3:
//                                courseInfoVo.setVerifyComment(userActivityTaskInfo.getVerifyComment());
//                                courseInfoVo.setActivityStatus(5);
//                                break;
//                            case 4:
//                                break;
//                            default:
//                                break;
//                        }
//                    }
//                }
//            }
//
//        } else {
//            courseInfoVo.setActivityStatus(userActivityInfo.getStatus());
//        }
        courseInfoVo.setActivityStatus(userActivityInfo.getStatus());
        // 6、设置视频学习状态
        userVideoService.setVideoStudyStatus(dto, courseInfoVo);
        courseInfoVo.setSubTitle(activityInfo.getSubTitle());
        courseInfoVo.setActivityType(activityInfo.getType());
        courseInfoVo.setActivityName(activityInfo.getName());
        courseInfoVo.setSubmitGanWu(activityInfo.getSubmitGanWu());
        log.info(":>>> 结束获取课程信息:{}", JSON.toJSON(courseInfoVo));
        return courseInfoVo;
    }

    public boolean courseVideoStudy(CourseInfoDTO dto) {
        UserPO userPO = dto.getUserPO();
//        if (StringUtils.isBlank(dto.getUserId()) || StringUtils.isBlank(userPO.getMobile())) {
        if (StringUtils.isBlank(dto.getUserId())) {
            throw new BusinessException("只有授权绑定手机号才能播放");
        }
        // 1、查询课程信息
        Query courseQuery = new Query(Criteria.where("id").is(dto.getCourseId()).and("deleted").is(false));
        ActivityCourse activityInfo = mongoTemplate.findOne(courseQuery, ActivityCourse.class);
        if (activityInfo == null) {
            throw new BusinessException("课程信息不存在");
        }
        // 2、查询视频信息
        Query videoQuery = new Query(Criteria.where("id").is(dto.getVideoId()).and("valid").is(1));
        ActivityCourseVideo video = mongoTemplate.findOne(videoQuery, ActivityCourseVideo.class);
        if (video == null) {
            throw new BusinessException("视频信息不存在");
        }
        int status = userVideoService.getActivityStatus(dto.getUserId(), dto.getAppId(), dto.getActivityId());
        if (video.getTryPlay() != 2 && status < ActivityVideoStatusEnum.STUDYING.getType()) {
            throw new BusinessException("视频未解锁");
        }
        // 3.图片课程处理
        if (activityInfo.getCourseType() == 1) {
            dto.setCurrentDuration(20);
            video.setTotalDuration(20);
        }
        // 4.保存用户视频学习信息
        userVideoService.saveUserVideo(dto, video.getTotalDuration());
        return true;
    }

    public CourseVideoVo getVideoDetail(UserVideoDTO dto) {
        // 查询视频信息
        Query videoQuery = new Query(Criteria.where("id").is(dto.getVideoId()).and("valid").is(1));
        ActivityCourseVideo video = mongoTemplate.findOne(videoQuery, ActivityCourseVideo.class);
        if (video == null) {
            throw new BusinessException("视频信息不存在");
        }
        CourseVideoVo vo = liteHomeCourseConvert.activityCourseVideoDTOToVideo(video);
        vo.setDescription(video.getDescription());
        UserActivityDTO userActivityDTO = userVideoService.getUserActivityInfo(dto.getUserId(), dto.getAppId(), dto.getActivityId());
        int status = userActivityDTO.getStatus();
        if (StringUtils.isBlank(dto.getUserId()) || status < ActivityVideoStatusEnum.STUDYING.getType()) {
            //不试看
            if (video.getTryPlay() != 2) {
                vo.setStatus(CourseVideoEnum.NOT_START.getType());
                return vo;
            }
        }
        // 查询用户学习状态
        UserCourseVideoStudy study = userVideoService.getCourseVideoByVideoId(dto.getUserId(), dto.getAppId(), video.getCourseId(), dto.getVideoId());

        if (status >= ActivityVideoStatusEnum.DO_THE_TITLE.getType()) {
            vo.setStatus(CourseVideoEnum.COMPLETE.getType());
            return vo;
        }
        vo.setStatus(study == null ? CourseVideoEnum.NOT_START.getType() : study.getStatus());
        return vo;
    }

    public CourseOrderVo createOrder(CourseInfoDTO dto) {
        // 1、查询活动信息
        QueryWrapper activeQuery = new QueryWrapper();
        activeQuery.select("id", "startTime", "endTime", "courseId").where("id", dto.getActivityId());
        CourseSimpleActivityEntity activity = mongoTemplate.findOne(activeQuery, CourseSimpleActivityEntity.class);
        if (activity == null) {
            throw new BusinessException("活动信息不存在");
        }
        Date date = new Date();
        if (activity.getStartTime() != null && date.before(activity.getStartTime())) {
            throw new BusinessException("活动未开始");
        }
        if (activity.getEndTime() != null && date.after(activity.getEndTime())) {
            throw new BusinessException("活动已经结束");
        }
        // 2、查询课程
        String courseId = activity.getCourseId();
        dto.setCourseId(courseId);
        Query courseQuery = new Query(Criteria.where("id").is(courseId).and("deleted").is(false));
        ActivityCourse activityCourse = mongoTemplate.findOne(courseQuery, ActivityCourse.class);
        if (activityCourse == null) {
            throw new BusinessException("课程信息不存在");
        }
        String key = "course.video.create.order.userId:%s";
        key = String.format(key, courseId);
        log.info("LiteHomeService,userId:{} key:{} createOrder add lock", dto.getUserId(), key);
        if (!lockService.tryLock(key, 1, TimeUnit.MINUTES)) {
            throw new BusinessException("请不要重复操作");
        }
        Triple<Boolean, Object, String> result = null;
        try {
            if (activityCourse.getPrice() <= 0) {
                // 1、0元报名参加活动
                result = userVideoService.dealUserJoinActivity(dto.getAppId(), dto.getUserId(), dto.getActivityId(), courseId);
                if (result.getLeft()) {
                    // 添加报名积分
                    userPointsCourseStudyService.endStudy(dto.getUserPO(), dto.getUserId(), dto.getPlatform(), dto.getAppId(), null);
                    // 添加报名信息
                    dto.getUserPO().setSignUpVideo(Boolean.TRUE);
                    dto.getUserPO().setActivityChannelId(dto.getActivityChannelId());
                    wechatMiniQaService.updateAfterSignUpUserInfo(dto.getActivityId(), dto.getUserPO());
                    if (StringUtils.isBlank(dto.getActivityChannelId())) {
                        userInviteRecordService.updateInvitedStatus(dto.getUserId(), dto.getActivityId());
                    }
                    return new CourseOrderVo(0, result.getMiddle());
                }
            } else {
                // 2、非0元获取支付信息
                result = userCourseOrderService.getPayInfo(dto, activityCourse);
                if (result.getLeft()) {
                    return new CourseOrderVo(1, result.getMiddle());
                }
            }
        } catch (Exception e) {
            log.error("LiteHomeService,userId:{}, key:{} createOrder error", dto.getUserId(), key, e);
        } finally {
            log.info("LiteHomeService,userId:{}, key:{} createOrder unlock success", dto.getUserId(), key);
            lockService.unLock(key);
        }
        throw new BusinessException(result != null ? result.getRight() : "创建订单异常");
    }

    public Page<ActivityResultVo> getHotList(HotActivityDTO dto) {
        // 查询发布活动
        Set<String> activityIdList = getPublishActivityIdList(dto.getAppId());
        // 查询活动信息
        QueryWrapper activeQuery = new QueryWrapper();
        activeQuery.select("id", "type", "name", "imageUrl", "subImageUrl", "thirdCourseUrl", "h5OfficialQrcode", "courseId", "startTime", "endTime", "tags", "hotPriority", "hoted");
        activeQuery.where("hoted", true);
        activeQuery.in("id", activityIdList);
        activeQuery.with(Sort.by(Sort.Order.desc("hotPriority")));
        long count = mongoTemplate.count(activeQuery, CourseSimpleActivityEntity.class);
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        activeQuery.with(pageRequest);
        List<CourseSimpleActivityEntity> list = mongoTemplate.find(activeQuery, CourseSimpleActivityEntity.class);
        List<ActivityResultVo> result = liteHomeCourseConvert.simActivityToResultVo(list, false);
        return PageableExecutionUtils.getPage(result, pageRequest, () -> count);
    }


    public Page<ActivityResultVo> getRecommendList(RecommendActivityDTO dto) {
        // 查询发布活动
        Set<String> activityIdList = getPublishActivityIdList(dto.getAppId());
        // 热门活动前三个
        QueryWrapper hotQuery = new QueryWrapper();
        hotQuery.select("id").in("id", activityIdList).where("hoted", true).with(Sort.by(Sort.Order.desc("hotPriority"))).with(PageRequest.of(0, 3));
        List<CourseSimpleActivityEntity> hotList = mongoTemplate.find(hotQuery, CourseSimpleActivityEntity.class);
        Set<String> hotAidList = hotList.stream().map(CourseSimpleActivityEntity::getId).collect(Collectors.toSet());
        // 推荐活动去除热门前三
        activityIdList.removeAll(hotAidList);
        // 查询推荐活动信息
        QueryWrapper activeQuery = new QueryWrapper();
        activeQuery.select("id", "name", "hoted", "type", "imageUrl", "subImageUrl", "h5OfficialQrcode", "courseId", "startTime", "endTime", "tags", "recommendPriority");
        activeQuery.with(Sort.by(Sort.Order.desc("recommendPriority")));
        activeQuery.in("id", activityIdList);
        if (StringUtils.isNotBlank(dto.getCategoryId())) {
            activeQuery.where("categoryId", dto.getCategoryId());
        }
        long count = mongoTemplate.count(activeQuery, CourseSimpleActivityEntity.class);
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        activeQuery.with(pageRequest);
        List<CourseSimpleActivityEntity> list = mongoTemplate.find(activeQuery, CourseSimpleActivityEntity.class);
        List<ActivityResultVo> result = liteHomeCourseConvert.simActivityToResultVo(list, false);
        return PageableExecutionUtils.getPage(result, pageRequest, () -> count);
    }

    public Page<ActivityResultVo> getRecommendPageHomeList(RecommendActivityDTO dto) {
        // 查询发布活动
        //Set<String> activityIdList = getPublishActivityIdList(dto.getAppId());
        QueryWrapper activeQuery = new QueryWrapper();
        activeQuery.select("id", "name", "hoted", "type", "imageUrl", "subImageUrl", "h5OfficialQrcode", "courseId", "startTime", "endTime", "tags", "priority",
                "showJoinNum", "initJoinNum", "randomInitJoinNum", "simpleAcType", "simpleAcUrl");
        activeQuery.with(Sort.by(Sort.Order.desc("priority")));
        //activeQuery.in("id", activityIdList);
        if (StringUtils.isNotBlank(dto.getCategoryId())) {
            activeQuery.where("categoryId", dto.getCategoryId());
        }
        long count = mongoTemplate.count(activeQuery, CourseSimpleActivityEntity.class);
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        activeQuery.with(pageRequest);
        List<CourseSimpleActivityEntity> list = mongoTemplate.find(activeQuery, CourseSimpleActivityEntity.class);
        List<ActivityResultVo> result = liteHomeCourseConvert.simActivityToResultVo(list, false);
        return PageableExecutionUtils.getPage(result, pageRequest, () -> count);
    }

    public Set<String> getPublishActivityIdList(String appId) {
        Query query = new Query(Criteria.where("appId").is(appId));
        List<ActivityPlatformConfig> configList = mongoTemplate.find(query, ActivityPlatformConfig.class);
        return configList.stream().map(ActivityPlatformConfig::getActivityId).collect(Collectors.toSet());
    }

    public RecruitmentActivityDetailVo getRecruitmentActivityById(String activityId) {
        List<String> fields = Lists.newArrayList("id", "shareName", "shareImageUrl", "detail", "imageUrl", "name", "simpleAcType", "simpleAcUrl");
        CourseSimpleActivityEntity activityInfo = simpleActivityService.findFieldsById(activityId, fields, CourseSimpleActivityEntity.class);
        if (activityInfo == null) {
            throw new BusinessException("活动信息不存在");
        }
        RecruitmentActivityDetailVo detailVo = new RecruitmentActivityDetailVo();
        detailVo.setDetail(activityInfo.getDetail());
        detailVo.setSimpleAcType(activityInfo.getSimpleAcType());
        detailVo.setSimpleAcUrl(activityInfo.getSimpleAcUrl());
        detailVo.setShareImageUrl(activityInfo.getShareImageUrl());
        detailVo.setShareName(activityInfo.getShareName());
        detailVo.setActivityId(activityInfo.getId());
        detailVo.setName(activityInfo.getName());
        return detailVo;
    }

    public KosActivityDetailVo getKosActivityDetail(KosActivityDTO dto) {
        List<String> fields = Lists.newArrayList("id", "shareName", "shareImageUrl", "imageUrl", "name", "kosPrice", "kosBeforeContent", "kosEndContent", "kosEndNotCodeContent");
        CourseSimpleActivityEntity activityInfo = simpleActivityService.findFieldsById(dto.getActivityId(), fields, CourseSimpleActivityEntity.class);
        if (activityInfo == null) {
            throw new BusinessException("活动信息不存在");
        }
        KosActivityDetailVo detailVo = new KosActivityDetailVo();
        detailVo.setKosPrice(activityInfo.getKosPrice());
        detailVo.setKosBeforeContent(activityInfo.getKosBeforeContent());
        detailVo.setKosEndContent(activityInfo.getKosEndContent());
        detailVo.setKosEndNotCodeContent(activityInfo.getKosEndNotCodeContent());
        detailVo.setShareImageUrl(activityInfo.getShareImageUrl());
        detailVo.setShareName(activityInfo.getShareName());
        detailVo.setActivityId(activityInfo.getId());
        detailVo.setName(activityInfo.getName());
        userKosService.setRedeemCodeAndStatus(dto, detailVo);
        return detailVo;
    }

    public Page<RegisterActivityDetailVo> getUserRegisterActivityList(RegisterActivityDTO dto) {
        // 查询发布活动
        Set<String> activityIdList = getPublishActivityIdList(dto.getAppId());
        // 查询参与的活动
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("activityId", "id", "joined");
        queryWrapper.in("userId", dto.getUserIdList());
        queryWrapper.in("activityId", activityIdList);
        List<UserParticipateActivityInfo> activityInfo = mongoTemplate.find(queryWrapper, UserParticipateActivityInfo.class);
        Set<String> parAidList = activityInfo.stream().filter(UserParticipateActivityInfo::getJoined).map(UserParticipateActivityInfo::getActivityId).collect(Collectors.toSet());
        QueryWrapper activeQuery = new QueryWrapper();
        activeQuery.select("id", "name", "type", "imageUrl", "subImageUrl", "h5OfficialQrcode", "courseId", "startTime", "endTime", "tags", "recommendPriority");
        activeQuery.in("id", parAidList);
        activeQuery.with(Sort.by(Sort.Order.desc("id")));
        Date date = new Date();
        if (dto.getType() == 0) {
            activeQuery.addCriteria(Criteria.where("startTime").lte(date).and("endTime").gt(date));
        } else {
            activeQuery.addCriteria(Criteria.where("endTime").lte(date));
        }
        long count = mongoTemplate.count(activeQuery, CourseSimpleActivityEntity.class);
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        activeQuery.with(pageRequest);
        List<CourseSimpleActivityEntity> list = mongoTemplate.find(activeQuery, CourseSimpleActivityEntity.class);
        List<RegisterActivityDetailVo> result = liteHomeCourseConvert.simActivityToJoinVo(list);
        return PageableExecutionUtils.getPage(result, pageRequest, () -> count);
    }

    public String getThirdCourseUrl(ThirdCourseDTO dto) {
        QueryWrapper activeQuery = new QueryWrapper();
        activeQuery.select("id", "name", "type", "thirdCourseUrl", "courseId", "startTime", "endTime");
        activeQuery.where("id", dto.getActivityId());
        CourseSimpleActivityEntity activityInfo = mongoTemplate.findOne(activeQuery, CourseSimpleActivityEntity.class);
        if (activityInfo == null) {
            throw new BusinessException("活动信息不存在");
        }
        String url = activityInfo.getThirdCourseUrl();
        String courseId = activityInfo.getCourseId();
        if (StringUtils.isAnyBlank(url, courseId)) {
            throw new BusinessException("第三方视频信息不存在");
        }
        String mobile = dto.getUserPO().getMobile();
        if (StringUtils.isBlank(mobile)) {
            throw new BusinessException("手机号为空，请先授权");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("course_id", courseId);
        params.put("open_id", dto.getUserPO().getOpenId());
        try {
            String encodePhone = CryptoDEUtil.encryptBy3DesAndBase64(mobile, CryptoDEUtil.SERCRET_KEY);
            Base64.Encoder encoder = Base64.getUrlEncoder();
            params.put("mobile", encoder.encodeToString(encodePhone.getBytes()));
        } catch (Exception e) {
            log.error("getThirdCourseUrl,error:{}", e);
            throw new BusinessException("获取加密手机号错误");
        }
        UserInfoExtend userInfoExtend = userInfoExtendService.findUserInfoByUserId(dto.getUserPO());
        if (userInfoExtend != null) {
            if (StringUtils.isNotBlank(userInfoExtend.getName())) {
                params.put("name", userInfoExtend.getName());
            }
            if (StringUtils.isNotBlank(userInfoExtend.getUniversityName())) {
                params.put("school", userInfoExtend.getUniversityName());
            }
        }
        return getUrl(url, params);
    }

    public void updateUserInfo(UserLogoSaveDTO dto) {
        Query query = new Query().addCriteria(Criteria.where("openId").is(dto.getOpenId()));
        Update update = new Update();
        update.set("avatarUrl", dto.getAvatarUrl());
        update.set("nickName", dto.getNickName());
        update.set("binded", true);
        mongoTemplate.updateFirst(query, update, WechatMiniUserPO.class);
    }

    public String getUrl(String baseUrl, Map<String, Object> params) {
        List<String> list = params.entrySet().stream().map(item -> item.getKey() + "=" + item.getValue()).collect(Collectors.toList());
        String strParam = String.join("&", list);
        return baseUrl + "?" + strParam;
    }

    public Object createKosOrder(KosActivityDTO dto) {
        // 1、查询活动信息
        List<String> fields = Lists.newArrayList("id", "startTime", "endTime", "kosPrice", "name", "kosPrice");
        CourseSimpleActivityEntity activityInfo = simpleActivityService.findFieldsById(dto.getActivityId(), fields, CourseSimpleActivityEntity.class);
        if (activityInfo == null) {
            throw new BusinessException("活动信息不存在");
        }
        Date date = new Date();
        if (activityInfo.getStartTime() != null && date.before(activityInfo.getStartTime())) {
            throw new BusinessException("活动未开始");
        }
        if (activityInfo.getEndTime() != null && date.after(activityInfo.getEndTime())) {
            throw new BusinessException("活动已经结束");
        }
        if (activityInfo.getKosPrice() == null || activityInfo.getKosPrice() <= 0) {
            throw new BusinessException("金额异常");
        }
        Triple<Boolean, Object, String> result = userKosService.createKosOrder(dto, activityInfo);
        if (!result.getLeft()) {
            throw new BusinessException(result.getRight());
        }
        return result.getMiddle();
    }

    public String miliLogin(UserPO userPO) {
        String mobile = userPO.getMobile();
        if (StringUtils.isBlank(mobile)) {
            throw new BusinessException("手机号为空，请先授权");
        }
        if (StringUtils.isBlank(userPO.getOpenId())) {
            throw new BusinessException("openId为空，请先授权");
        }
        Pair<Boolean, String> re = miliThirdService.getMiliAccessToken(mobile, userPO.getOpenId());
        if (!re.getLeft()) {
            throw new BusinessException(re.getValue());
        }
        String url = "https://mxtd.milixf.com/#/pages/sdk-entry/index?token=" + re.getRight();
        return url;
    }

    public Map getWechatMenu(UserPO userPO) {
//        Config config = ConfigService.getAppConfig();
//        String cnf = config.getProperty("wechat.menu", "{}");
//        Map map = JSON.parseObject(cnf, Map.class);
        SystemApolloConfig systemApolloConfig = systemApolloConfigService.find();
        Map map = systemApolloConfig.getWechatMenu2();
        return map;
    }
}